package avicit.bdp.dds.server.worker.processor;


import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.common.thread.Stopper;
import avicit.bdp.dds.common.thread.ThreadUtils;
import avicit.bdp.dds.remote.NettyRemotingClient;
import avicit.bdp.dds.remote.command.Command;
import avicit.bdp.dds.remote.config.NettyClientConfig;
import avicit.bdp.dds.remote.utils.Host;
import avicit.bdp.dds.server.registry.ZookeeperRegistryCenter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  taks callback service
 */
@Service
public class TaskCallbackService {

    private final Logger logger = LoggerFactory.getLogger(TaskCallbackService.class);
    private static final int [] RETRY_BACKOFF = { 1, 2, 3, 5, 10, 20, 40, 100, 100, 100, 100, 200, 200, 200 };

    /**
     *  remote channels
     */
    private static final ConcurrentHashMap<String, NettyRemoteChannel> REMOTE_CHANNELS = new ConcurrentHashMap<>();

    /**
     * zookeeper register center
     */
    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;


    /**
     * netty remoting client
     */
    private final NettyRemotingClient nettyRemotingClient;


    public TaskCallbackService(){
        final NettyClientConfig clientConfig = new NettyClientConfig();
        this.nettyRemotingClient = new NettyRemotingClient(clientConfig);
    }

    /**
     *  add callback channel
     * @param taskInstanceId taskInstanceId
     * @param channel  channel
     */
    public void addRemoteChannel(String taskInstanceId, NettyRemoteChannel channel){
        REMOTE_CHANNELS.put(taskInstanceId, channel);
    }

    /**
     *  get callback channel
     * @param taskInstanceId taskInstanceId
     * @return callback channel
     */
    private NettyRemoteChannel getRemoteChannel(String taskInstanceId){
        NettyRemoteChannel nettyRemoteChannel = REMOTE_CHANNELS.get(taskInstanceId);
        if(nettyRemoteChannel == null){
            throw new IllegalArgumentException("nettyRemoteChannel is empty, should call addRemoteChannel first");
        }
        if(nettyRemoteChannel.isActive()){
            return nettyRemoteChannel;
        }
        Channel newChannel = nettyRemotingClient.getChannel(nettyRemoteChannel.getHost());
        if(newChannel != null){
            return getRemoteChannel(newChannel, nettyRemoteChannel.getOpaque(), taskInstanceId);
        }
        logger.warn("original master : {} for task : {} is not reachable, random select master",
                nettyRemoteChannel.getHost(),
                taskInstanceId);
        Set<String> masterNodes = null;
        int ntries = 0;
        while (Stopper.isRunning()) {
            masterNodes = zookeeperRegistryCenter.getMasterNodesDirectly();
            if (CollectionUtils.isEmpty(masterNodes)) {
                logger.info("try {} times but not find any master for task : {}.",
                        ntries + 1,
                        taskInstanceId);
                masterNodes = null;
                ThreadUtils.sleep(pause(ntries++));
                continue;
            }
            logger.info("try {} times to find {} masters for task : {}.",
                    ntries + 1,
                    masterNodes.size(),
                    taskInstanceId);
            for (String masterNode : masterNodes) {
                newChannel = nettyRemotingClient.getChannel(Host.of(masterNode));
                if (newChannel != null) {
                    return getRemoteChannel(newChannel, nettyRemoteChannel.getOpaque(), taskInstanceId);
                }
            }
            masterNodes = null;
            ThreadUtils.sleep(pause(ntries++));
        }

        throw new IllegalStateException(String.format("all available master nodes : %s are not reachable for task: {}", masterNodes, taskInstanceId));
    }


    public int pause(int ntries){
        return Constants.SLEEP_TIME_MILLIS * RETRY_BACKOFF[ntries % RETRY_BACKOFF.length];
    }


    private NettyRemoteChannel getRemoteChannel(Channel newChannel, long opaque, String taskInstanceId){
        NettyRemoteChannel remoteChannel = new NettyRemoteChannel(newChannel, opaque);
        addRemoteChannel(taskInstanceId, remoteChannel);
        return remoteChannel;
    }

    /**
     *  remove callback channels
     * @param taskInstanceId taskInstanceId
     */
    public void remove(String taskInstanceId){
        REMOTE_CHANNELS.remove(taskInstanceId);
    }

    /**
     *  send ack
     * @param taskInstanceId taskInstanceId
     * @param command command
     */
    public void sendAck(String taskInstanceId, Command command){
        NettyRemoteChannel nettyRemoteChannel = getRemoteChannel(taskInstanceId);
        nettyRemoteChannel.writeAndFlush(command);
    }

    /**
     *  send result
     *
     * @param taskInstanceId taskInstanceId
     * @param command command
     */
    public void sendResult(String taskInstanceId, Command command){
        logger.info("task:[{}] call back send result, command:{}", taskInstanceId, command);
        NettyRemoteChannel nettyRemoteChannel = getRemoteChannel(taskInstanceId);
        nettyRemoteChannel.writeAndFlush(command).addListener(new ChannelFutureListener(){

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if(future.isSuccess()){
                    remove(taskInstanceId);
                    return;
                }
            }
        });
    }
}
